import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Gauge, Clock, Trophy, Star, Zap, CheckCircle, XCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface ProcessingSpeedTestProps {
  onComplete: (result: TestResult) => void;
}

interface Task {
  id: number;
  type: 'symbol-digit' | 'visual-search' | 'simple-comparison';
  content: any;
  correctAnswer: string | number | boolean;
}

interface SymbolDigitTask {
  symbol: string;
  options: number[];
  correctDigit: number;
}

interface VisualSearchTask {
  target: string;
  distractors: string[];
  targetPresent: boolean;
}

interface ComparisonTask {
  item1: string;
  item2: string;
  same: boolean;
}

interface FeedbackState {
  show: boolean;
  correct: boolean;
  reactionTime: number;
}

const SYMBOLS = ['◆', '★', '▲', '●', '■', '◇', '☆', '△', '○', '□'];
const SYMBOL_DIGIT_MAP: Record<string, number> = {
  '◆': 1, '★': 2, '▲': 3, '●': 4, '■': 5,
  '◇': 6, '☆': 7, '△': 8, '○': 9, '□': 0
};

const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const NUMBERS = '0123456789';

export function ProcessingSpeedTest({ onComplete }: ProcessingSpeedTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentTask, setCurrentTask] = useState(0);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [responses, setResponses] = useState<(string | number | boolean)[]>([]);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [accuracy, setAccuracy] = useState<boolean[]>([]);
  const [timeLeft, setTimeLeft] = useState(240); // 4分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [taskStartTime, setTaskStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [correctStreak, setCorrectStreak] = useState(0);
  const [maxStreak, setMaxStreak] = useState(0);
  const [feedback, setFeedback] = useState<FeedbackState>({ show: false, correct: false, reactionTime: 0 });
  const [awaitingResponse, setAwaitingResponse] = useState(true);

  const TOTAL_TASKS = 90;
  const feedbackTimeoutRef = useRef<NodeJS.Timeout>();

  const generateSymbolDigitTask = (): SymbolDigitTask => {
    const symbol = SYMBOLS[Math.floor(Math.random() * SYMBOLS.length)];
    const correctDigit = SYMBOL_DIGIT_MAP[symbol];
    const options = [correctDigit];
    
    while (options.length < 4) {
      const option = Math.floor(Math.random() * 10);
      if (!options.includes(option)) {
        options.push(option);
      }
    }
    
    // 打乱选项
    for (let i = options.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [options[i], options[j]] = [options[j], options[i]];
    }
    
    return { symbol, options, correctDigit };
  };

  const generateVisualSearchTask = (): VisualSearchTask => {
    const target = LETTERS[Math.floor(Math.random() * LETTERS.length)];
    const distractorCount = Math.floor(Math.random() * 8) + 12; // 12-19个干扰项
    const targetPresent = Math.random() < 0.5;
    
    const distractors: string[] = [];
    for (let i = 0; i < distractorCount; i++) {
      let distractor;
      do {
        distractor = LETTERS[Math.floor(Math.random() * LETTERS.length)];
      } while (distractor === target);
      distractors.push(distractor);
    }
    
    if (targetPresent) {
      // 在随机位置插入目标
      const insertIndex = Math.floor(Math.random() * (distractors.length + 1));
      distractors.splice(insertIndex, 0, target);
    }
    
    return { target, distractors, targetPresent };
  };

  const generateComparisonTask = (): ComparisonTask => {
    const length = Math.floor(Math.random() * 3) + 3; // 3-5位
    const item1 = Array.from({ length }, () => 
      Math.random() < 0.5 ? LETTERS[Math.floor(Math.random() * LETTERS.length)] :
                           NUMBERS[Math.floor(Math.random() * NUMBERS.length)]
    ).join('');
    
    const same = Math.random() < 0.5;
    let item2 = item1;
    
    if (!same) {
      // 改变1-2个字符
      const changeCount = Math.floor(Math.random() * 2) + 1;
      const chars = item2.split('');
      for (let i = 0; i < changeCount; i++) {
        const index = Math.floor(Math.random() * chars.length);
        const isLetter = /[A-Z]/.test(chars[index]);
        chars[index] = isLetter ? 
          LETTERS[Math.floor(Math.random() * LETTERS.length)] :
          NUMBERS[Math.floor(Math.random() * NUMBERS.length)];
      }
      item2 = chars.join('');
    }
    
    return { item1, item2, same };
  };

  const generateTasks = (): Task[] => {
    const newTasks: Task[] = [];
    const taskTypes: Array<'symbol-digit' | 'visual-search' | 'simple-comparison'> = 
      ['symbol-digit', 'visual-search', 'simple-comparison'];
    
    for (let i = 0; i < TOTAL_TASKS; i++) {
      const type = taskTypes[i % taskTypes.length];
      let content: any;
      let correctAnswer: string | number | boolean;
      
      switch (type) {
        case 'symbol-digit':
          content = generateSymbolDigitTask();
          correctAnswer = content.correctDigit;
          break;
        case 'visual-search':
          content = generateVisualSearchTask();
          correctAnswer = content.targetPresent;
          break;
        case 'simple-comparison':
          content = generateComparisonTask();
          correctAnswer = content.same;
          break;
      }
      
      newTasks.push({
        id: i + 1,
        type,
        content,
        correctAnswer
      });
    }
    
    return newTasks;
  };

  useEffect(() => {
    if (stage === 'test') {
      const newTasks = generateTasks();
      setTasks(newTasks);
      setTaskStartTime(Date.now());
    }
  }, [stage]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
  };

  const handleResponse = (response: string | number | boolean) => {
    if (!awaitingResponse) return;
    
    const reactionTime = Date.now() - taskStartTime;
    const task = tasks[currentTask];
    
    // Safety check for task
    if (!task) {
      console.error('No task available for response');
      return;
    }
    
    const correct = response === task.correctAnswer;
    
    setAwaitingResponse(false);
    setResponses(prev => [...prev, response]);
    setReactionTimes(prev => [...prev, reactionTime]);
    setAccuracy(prev => [...prev, correct]);
    
    // 显示即时反馈
    setFeedback({ show: true, correct, reactionTime });
    
    if (correct) {
      setScore(prev => prev + 1);
      setCorrectStreak(prev => {
        const newStreak = prev + 1;
        setMaxStreak(current => Math.max(current, newStreak));
        return newStreak;
      });
    } else {
      setCorrectStreak(0);
    }

    // 1秒后进入下一任务
    feedbackTimeoutRef.current = setTimeout(() => {
      setFeedback({ show: false, correct: false, reactionTime: 0 });
      setAwaitingResponse(true);
      
      if (currentTask < tasks.length - 1) {
        setCurrentTask(prev => prev + 1);
        setTaskStartTime(Date.now());
      } else {
        setStage('results');
      }
    }, 1000);
  };

  const handleComplete = () => {
    // Safety checks for data integrity
    if (!accuracy.length || !reactionTimes.length || !tasks.length) {
      console.error('Incomplete test data for completion');
      return;
    }

    const totalCorrect = accuracy.filter(a => a).length;
    const overallAccuracy = accuracy.length > 0 ? Math.round((totalCorrect / accuracy.length) * 100) : 0;
    const averageRT = reactionTimes.length > 0 ? 
      Math.round(reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length) : 0;
    
    // 优化的评分算法
    const timeUsedMinutes = (Date.now() - startTime) / (1000 * 60);
    const correctPerMinute = timeUsedMinutes > 0 ? Math.round(totalCorrect / timeUsedMinutes) : 0;
    
    // 更精准的评分系统
    let finalScore = 0;
    
    // 基础准确率贡献 (50%)
    finalScore += overallAccuracy * 0.5;
    
    // 处理速度贡献 (30%) - 基于每分钟正确数
    const speedScore = Math.min(100, correctPerMinute * 2); // 每分钟30个正确答案得满分
    finalScore += speedScore * 0.3;
    
    // 反应时间稳定性 (15%) - 奖励一致的表现
    const rtVariance = reactionTimes.length > 1 ? 
      reactionTimes.reduce((sum, rt) => sum + Math.pow(rt - averageRT, 2), 0) / reactionTimes.length : 0;
    const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 50);
    finalScore += consistencyScore * 0.15;
    
    // 连击奖励 (5%) - 奖励连续正确
    const streakBonus = Math.min(100, (maxStreak / totalCorrect) * 100);
    finalScore += streakBonus * 0.05;
    
    finalScore = Math.round(Math.max(0, Math.min(100, finalScore)));

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 各类型任务准确率 - 添加安全检查
    const symbolDigitTasks = tasks.filter(t => t && t.type === 'symbol-digit').length;
    const symbolDigitCorrect = accuracy.filter((a, i) => 
      tasks[i] && tasks[i].type === 'symbol-digit' && a).length;
    const symbolDigitAccuracy = symbolDigitTasks > 0 ? Math.round((symbolDigitCorrect / symbolDigitTasks) * 100) : 0;
    
    const visualSearchTasks = tasks.filter(t => t && t.type === 'visual-search').length;
    const visualSearchCorrect = accuracy.filter((a, i) => 
      tasks[i] && tasks[i].type === 'visual-search' && a).length;
    const visualSearchAccuracy = visualSearchTasks > 0 ? Math.round((visualSearchCorrect / visualSearchTasks) * 100) : 0;
    
    const comparisonTasks = tasks.filter(t => t && t.type === 'simple-comparison').length;
    const comparisonCorrect = accuracy.filter((a, i) => 
      tasks[i] && tasks[i].type === 'simple-comparison' && a).length;
    const comparisonAccuracy = comparisonTasks > 0 ? Math.round((comparisonCorrect / comparisonTasks) * 100) : 0;

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'processing-speed',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTasks: tasks.length,
        correctResponses: totalCorrect,
        overallAccuracy,
        averageReactionTime: averageRT,
        correctPerMinute,
        maxStreakLength: maxStreak,
        symbolDigitAccuracy,
        visualSearchAccuracy,
        comparisonAccuracy,
        processingSpeedIndex: correctPerMinute,
        consistencyScore: Math.round(consistencyScore),
        speedScore: Math.round(speedScore),
        streakBonus: Math.round(streakBonus)
      }
    };

    onComplete(result);
  };

  const renderTask = () => {
    const task = tasks[currentTask];
    if (!task) return null;

    switch (task.type) {
      case 'symbol-digit':
        const symbolTask = task.content as SymbolDigitTask;
        return (
          <div className="text-center space-y-6 relative">
            <h3 className="text-lg font-semibold text-slate-700 mb-4">找到对应的数字</h3>
            <div className="text-8xl font-bold text-slate-800 mb-6 relative">
              {symbolTask.symbol}
              
              {/* 即时反馈 */}
              <AnimatePresence>
                {feedback.show && (
                  <motion.div
                    initial={{ scale: 0, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0, opacity: 0 }}
                    className={`absolute -top-4 -right-4 w-16 h-16 rounded-full flex items-center justify-center ${
                      feedback.correct ? 'bg-green-500' : 'bg-red-500'
                    } shadow-lg`}
                  >
                    {feedback.correct ? 
                      <CheckCircle className="w-8 h-8 text-white" /> : 
                      <XCircle className="w-8 h-8 text-white" />
                    }
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
            
            {/* 反应时间显示 */}
            <AnimatePresence>
              {feedback.show && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="absolute top-full left-1/2 transform -translate-x-1/2 mt-4"
                >
                  <Badge variant="outline" className="bg-white/90 text-slate-600">
                    {feedback.reactionTime}ms
                  </Badge>
                </motion.div>
              )}
            </AnimatePresence>
            
            <AnimatePresence>
              {!feedback.show && awaitingResponse && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="grid grid-cols-2 sm:grid-cols-4 gap-4"
                >
                  {symbolTask.options.map((option, index) => (
                    <Button
                      key={index}
                      onClick={() => handleResponse(option)}
                      className="h-16 text-2xl font-bold bg-white hover:bg-blue-50 text-slate-800 border-2 border-slate-300 hover:border-blue-400 transition-all duration-200"
                      variant="outline"
                    >
                      {option}
                    </Button>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        );

      case 'visual-search':
        const searchTask = task.content as VisualSearchTask;
        return (
          <div className="text-center space-y-6 relative">
            <h3 className="text-lg font-semibold text-slate-700">找到目标字母</h3>
            <div className="text-4xl font-bold text-blue-600 mb-4">
              目标: {searchTask.target}
            </div>
            <div className="grid grid-cols-5 sm:grid-cols-7 gap-2 max-w-2xl mx-auto mb-6 relative">
              {searchTask.distractors.map((letter, index) => (
                <div
                  key={index}
                  className={`w-10 h-10 flex items-center justify-center text-lg font-semibold border rounded ${
                    letter === searchTask.target 
                      ? 'bg-blue-100 border-blue-400 text-blue-800' 
                      : 'bg-slate-50 border-slate-300 text-slate-700'
                  }`}
                >
                  {letter}
                </div>
              ))}
              
              {/* 即时反馈 */}
              <AnimatePresence>
                {feedback.show && (
                  <motion.div
                    initial={{ scale: 0, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0, opacity: 0 }}
                    className={`absolute -top-4 -right-4 w-12 h-12 rounded-full flex items-center justify-center ${
                      feedback.correct ? 'bg-green-500' : 'bg-red-500'
                    } shadow-lg`}
                  >
                    {feedback.correct ? 
                      <CheckCircle className="w-6 h-6 text-white" /> : 
                      <XCircle className="w-6 h-6 text-white" />
                    }
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
            
            {/* 反应时间显示 */}
            <AnimatePresence>
              {feedback.show && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="mb-6"
                >
                  <Badge variant="outline" className="bg-white/90 text-slate-600">
                    {feedback.reactionTime}ms
                  </Badge>
                </motion.div>
              )}
            </AnimatePresence>
            
            <AnimatePresence>
              {!feedback.show && awaitingResponse && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="flex justify-center gap-4"
                >
                  <Button
                    onClick={() => handleResponse(true)}
                    className="bg-green-500 hover:bg-green-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                  >
                    存在
                  </Button>
                  <Button
                    onClick={() => handleResponse(false)}
                    className="bg-red-500 hover:bg-red-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                  >
                    不存在
                  </Button>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        );

      case 'simple-comparison':
        const comparisonTask = task.content as ComparisonTask;
        return (
          <div className="text-center space-y-6 relative">
            <h3 className="text-lg font-semibold text-slate-700 mb-4">比较两个字符串是否相同</h3>
            <div className="space-y-4 relative">
              <div className="text-4xl font-mono font-bold text-slate-800 bg-slate-100 px-6 py-3 rounded-lg">
                {comparisonTask.item1}
              </div>
              <div className="text-2xl text-slate-500">vs</div>
              <div className="text-4xl font-mono font-bold text-slate-800 bg-slate-100 px-6 py-3 rounded-lg">
                {comparisonTask.item2}
              </div>
              
              {/* 即时反馈 */}
              <AnimatePresence>
                {feedback.show && (
                  <motion.div
                    initial={{ scale: 0, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0, opacity: 0 }}
                    className={`absolute top-1/2 -right-4 w-12 h-12 rounded-full flex items-center justify-center ${
                      feedback.correct ? 'bg-green-500' : 'bg-red-500'
                    } shadow-lg transform -translate-y-1/2`}
                  >
                    {feedback.correct ? 
                      <CheckCircle className="w-6 h-6 text-white" /> : 
                      <XCircle className="w-6 h-6 text-white" />
                    }
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
            
            {/* 反应时间显示 */}
            <AnimatePresence>
              {feedback.show && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="mt-4"
                >
                  <Badge variant="outline" className="bg-white/90 text-slate-600">
                    {feedback.reactionTime}ms
                  </Badge>
                </motion.div>
              )}
            </AnimatePresence>
            
            <AnimatePresence>
              {!feedback.show && awaitingResponse && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="flex justify-center gap-4 mt-8"
                >
                  <Button
                    onClick={() => handleResponse(true)}
                    className="bg-green-500 hover:bg-green-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                  >
                    相同
                  </Button>
                  <Button
                    onClick={() => handleResponse(false)}
                    className="bg-red-500 hover:bg-red-600 text-white px-8 py-3 font-semibold transition-all duration-200"
                  >
                    不同
                  </Button>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        );

      default:
        return null;
    }
  };

  // 清理定时器
  useEffect(() => {
    return () => {
      if (feedbackTimeoutRef.current) {
        clearTimeout(feedbackTimeoutRef.current);
      }
    };
  }, []);

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-amber-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-amber-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Gauge className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">信息处理速度测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您快速处理简单信息的能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-6 border border-amber-100">
              <h3 className="font-semibold text-amber-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p><strong>符号数字</strong>：根据符号找到对应的数字</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p><strong>视觉搜索</strong>：在字母阵列中找到目标字母</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p><strong>简单比较</strong>：判断两个字符串是否相同</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>每次回答后会显示正确/错误反馈和反应时间</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">5</span>
                  <p>尽可能快速准确地完成所有任务</p>
                </div>
              </div>
            </div>

            {/* 符号-数字映射表 */}
            <div className="bg-slate-50 rounded-xl p-4 border border-slate-200">
              <h4 className="font-semibold text-slate-700 mb-3 text-center">符号-数字对应表</h4>
              <div className="grid grid-cols-5 gap-2 text-center">
                {SYMBOLS.map((symbol, index) => (
                  <div key={symbol} className="flex flex-col items-center gap-1">
                    <div className="text-2xl">{symbol}</div>
                    <div className="text-lg font-semibold text-slate-600">{SYMBOL_DIGIT_MAP[symbol]}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl border border-amber-200">
                <div className="text-2xl font-bold text-amber-600 mb-1">90</div>
                <div className="text-sm text-amber-700">任务数量</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">4</div>
                <div className="text-sm text-orange-700">分钟限时</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-amber-50 to-orange-50 rounded-xl border border-amber-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">3</div>
                <div className="text-sm text-slate-700">任务类型</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-amber-600 to-orange-500 hover:from-amber-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    // Safety check - ensure we have tasks and valid current task
    if (!tasks.length || currentTask >= tasks.length) {
      return (
        <div className="max-w-2xl mx-auto text-center p-8">
          <p className="text-slate-600">正在加载测试任务...</p>
        </div>
      );
    }

    const progress = (currentTask / tasks.length) * 100;
    const task = tasks[currentTask];

    // Additional safety check for task
    if (!task) {
      return (
        <div className="max-w-2xl mx-auto text-center p-8">
          <p className="text-slate-600">正在准备下一个任务...</p>
        </div>
      );
    }

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-amber-100 text-amber-700 border-amber-300">
              任务 {currentTask + 1} / {tasks.length}
            </Badge>
            <Badge variant="outline" className={`${
              task.type === 'symbol-digit' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              task.type === 'visual-search' ? 'bg-green-100 text-green-700 border-green-300' :
              'bg-purple-100 text-purple-700 border-purple-300'
            }`}>
              {task.type === 'symbol-digit' ? '符号数字' :
               task.type === 'visual-search' ? '视觉搜索' : '简单比较'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
            {correctStreak >= 5 && (
              <div className="flex items-center gap-2 text-orange-600">
                <Zap className="w-4 h-4" />
                <span className="font-semibold">连对: {correctStreak}</span>
              </div>
            )}
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 测试区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-amber-200 shadow-lg">
          <CardContent className="py-8">
            <AnimatePresence mode="wait">
              <motion.div
                key={currentTask}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{ duration: 0.3 }}
              >
                {renderTask()}
              </motion.div>
            </AnimatePresence>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    // Safety check for results data
    if (!accuracy.length || !reactionTimes.length) {
      return (
        <div className="max-w-2xl mx-auto text-center p-8">
          <p className="text-slate-600">正在计算结果...</p>
        </div>
      );
    }

    const totalCorrect = accuracy.filter(a => a).length;
    const overallAccuracy = Math.round((totalCorrect / accuracy.length) * 100);
    const averageRT = Math.round(reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length);
    
    const timeUsedMinutes = (Date.now() - startTime) / (1000 * 60);
    const correctPerMinute = timeUsedMinutes > 0 ? Math.round(totalCorrect / timeUsedMinutes) : 0;
    
    // 重新计算最终分数以便显示
    let finalScore = 0;
    finalScore += overallAccuracy * 0.5;
    const speedScore = Math.min(100, correctPerMinute * 2);
    finalScore += speedScore * 0.3;
    const rtVariance = reactionTimes.length > 1 ? 
      reactionTimes.reduce((sum, rt) => sum + Math.pow(rt - averageRT, 2), 0) / reactionTimes.length : 0;
    const consistencyScore = Math.max(0, 100 - Math.sqrt(rtVariance) / 50);
    finalScore += consistencyScore * 0.15;
    const streakBonus = Math.min(100, (maxStreak / totalCorrect) * 100);
    finalScore += streakBonus * 0.05;
    finalScore = Math.round(Math.max(0, Math.min(100, finalScore)));

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-amber-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-amber-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-amber-600 to-orange-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">信息处理速度得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-amber-50 to-amber-100 rounded-xl border border-amber-200">
                <div className="text-2xl font-bold text-amber-600 mb-1">{correctPerMinute}</div>
                <div className="text-sm text-amber-700">正确/分钟</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">{averageRT}ms</div>
                <div className="text-sm text-orange-700">平均反应时</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">总准确率</span>
                <span className="font-semibold text-slate-800">{overallAccuracy}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">最长连对</span>
                <span className="font-semibold text-slate-800">{maxStreak}次</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">完成任务数</span>
                <span className="font-semibold text-slate-800">{totalCorrect}/{tasks.length}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">处理速度指数</span>
                <span className="font-semibold text-slate-800">{Math.round(speedScore)}</span>
              </div>
            </div>

            <div className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-4 border border-amber-100">
              <h3 className="font-semibold text-amber-900 mb-3 flex items-center gap-2">
                <Gauge className="w-5 h-5" />
                评分详情
              </h3>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-600">准确率得分 (50%)</span>
                  <span className="text-amber-600">+{Math.round(overallAccuracy * 0.5)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">处理速度 (30%)</span>
                  <span className="text-orange-600">+{Math.round(speedScore * 0.3)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">稳定性 (15%)</span>
                  <span className="text-blue-600">+{Math.round(consistencyScore * 0.15)}分</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">连击奖励 (5%)</span>
                  <span className="text-green-600">+{Math.round(streakBonus * 0.05)}分</span>
                </div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-amber-600 to-orange-500 hover:from-amber-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}